<template>
  <!--  未发布的团课-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团课名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入团课名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['subscribe:courseSubscribe:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['subscribe:courseSubscribe:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['subscribe:courseSubscribe:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['subscribe:courseSubscribe:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseSubscribeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="团课名称" align="center" prop="courseName"/>
      <el-table-column label="团课创建时间" align="center" prop="courseCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.courseCreateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否收费" align="center" prop="collectFee">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.collect_fee" :value="scope.row.collectFee"/>
        </template>
      </el-table-column>
      <el-table-column label="收费金额(元)" align="center" prop="collectFeeMoney">
        <template slot-scope="scope">
          <span>{{ scope.row.collectFeeMoney.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报名时间" align="center" prop="registrationTime" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.registrationTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止报名时间" align="center" prop="registrationDeadline" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.registrationDeadline }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="toggleDisableStatus(scope.row)"
          >发布团课
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['subscribe:courseSubscribe:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['subscribe:courseSubscribe:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团课信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="close" width="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="form-container"
        :inline="true"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="名称" prop="courseName">
              <el-input v-model="form.courseName" placeholder="请输入团课名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--付款方式-->
            <el-form-item v-if="form.collectFee === 0" label="付款方式" prop="payWay">
              <el-radio-group v-model="form.payWay" size="medium">
                <el-radio :label="0">线上</el-radio>
                <el-radio :label="1">到付</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="是否收费" prop="collectFee">
              <el-radio-group v-model="form.collectFee" size="medium">
                <el-radio v-for="(item, index) in collectFee" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.collectFee === 0" label="收费金额" prop="collectFeeMoney">
              <el-input v-model="form.collectFeeMoney" placeholder="" maxlength="4" style="width: 220px">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="至少报名数" prop="registrationNumberLeast">
              <el-input v-model="form.registrationNumberLeast" placeholder="" maxlength="4" style="width: 220px">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大报名数" prop="registrationNumber">
              <el-input v-model="form.registrationNumber" placeholder="" maxlength="4" style="width: 220px">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="报名时间" prop="registrationTime">
              <el-date-picker
                v-model="form.registrationTime"
                type="datetime"
                placeholder="选择报名时间"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleDateChange('registrationTime')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 截止时间 -->
          <el-col :span="12">
            <el-form-item label="截止时间" prop="registrationDeadline">
              <el-date-picker
                v-model="form.registrationDeadline"
                type="datetime"
                placeholder="选择截止时间"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleDateChange('registrationDeadline')">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 开始时间 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="courseStartTime">
              <el-date-picker
                v-model="form.courseStartTime"
                type="datetime"
                placeholder="选择开始时间"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleDateChange('courseStartTime')"
                :readonly="isEditMode">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- 结束时间 -->
          <el-col :span="12">
            <el-form-item label="结束时间" prop="courseEndTime">
              <el-date-picker
                v-model="form.courseEndTime"
                type="datetime"
                placeholder="选择结束时间"
                :picker-options="pickerOptions"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleDateChange('courseEndTime')"
                :readonly="isEditMode">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--教练-->
            <el-form-item label="教练" prop="couchId">
              <el-select v-model="form.couchId">
                <el-option v-for="item in couchList" :key="item.id" :label="item.coachName"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="courseStatus">
              <el-radio-group v-model="form.courseStatus" size="medium">
                <el-radio v-for="(item, index) in courseStatusOptions" :key="index" :label="item.value"
                          :disabled="item.disabled">{{ item.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <h2 style="margin-left: 30px">图片</h2>
          <el-col :span="12">
            <el-form-item label="" style="display: flex; align-items: center;">
              <image-upload v-model="form.coverPic" style="margin-left: 30px"></image-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="描述" prop="courseDescribe">
              <el-input v-model="form.courseDescribe" type="textarea" placeholder="请输入团课描述"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '220px'}"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCourseSubscribe,
  getCourseSubscribe,
  delCourseSubscribe,
  addCourseSubscribe,
  updateCourseSubscribe,
  updateCourseStatus,
  getVenueMaxNumber,
  getCouchInfo
} from "@/api/subscribe/courseSubscribe";

export default {
  name: "CourseSubscribe",
  dicts: ['collect_fee', 'course_subscribe_type'],
  data() {
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < today.getTime();
        }
      },
      isEditMode: false, // 根据实际情况设置初始值
      couchList: [],//存放教练数组
      venueMaxNumber: 0,//场馆最大人数
      courseStatusOptions: [{
        label: "发布",
        value: 0
      }, {
        label: "待发布",
        value: 1
      }],
      collectFee: [{
        label: "免费",
        value: 1
      },
        {
          label: "收费",
          value: 0
        }],
      courseInfoData: {},
      coverPic: '',//团课图片
      // 租户标识
      venueUniqueIdentifier: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团课信息表格数据
      courseSubscribeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        courseStatus: 1,//未发布状态 1
      },
      // 表单参数
      form: {
        registrationTime: '',
        registrationDeadline: '',
        courseStartTime: '',
        courseEndTime: '',
        registrationNumber: 200,//设置最大报名数默认为200
      },
      // 表单校验
      rules: {
        registrationTime: [
          {required: true, message: '请填写报名时间', trigger: 'blur'},
          {validator: this.validateRegistrationTime, trigger: 'blur'}
        ],
        registrationDeadline: [
          {required: true, message: '请填写截止时间', trigger: 'blur'},
          {validator: this.validateRegistrationDeadline, trigger: 'blur'}
        ],
        courseStartTime: [{required: true, message: "请填写团课开始时间", trigger: "blur"}],
        payWay: [{required: true, message: "请填写付款方式", trigger: "blur"}],
        courseEndTime: [{required: true, message: "请填写团课结束时间", trigger: "blur"},
          {validator: this.validateEndTime, trigger: 'blur'}],
        registrationNumberLeast: [
          {required: true, message: '请输入至少报名数', trigger: 'blur'},
          {validator: this.validateLeastRegistrationNumber, trigger: 'blur'}
        ],
        registrationNumber: [
          {required: true, message: '请输入最大报名数', trigger: 'blur'},
          {validator: this.validateNumber, trigger: 'blur'}
        ],
        collectFee: [{required: true, message: "请选择是否收费", trigger: "blur"}],
        courseStatus: [{required: true, message: "请选择团课状态", trigger: "blur"}],
        couchId: [{required: true, message: "请选择教练", trigger: "blur"}],
        collectFeeMoney: [{required: true, message: "请输入收费金额", trigger: "blur"}],
        courseName: [
          {required: true, message: "请输入团课名称", trigger: "blur"},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        courseDescribe: [{required: true, message: "请输入团课描述", trigger: "blur"},
          {min: 5, max: 50, message: '不少于5个字符', trigger: 'blur'}]
      },
    };
  },
  created() {
    this.getList();
    //获取场馆最大人数
    // this.getVenueMaxNumber();
    //获取教练信息
    this.getCouchInfo();
  },
  methods: {
    handleDateChange(field) {
      // 获取选中的日期，确保秒数为00
      if (this.form[field]) {
        const date = new Date(this.form[field]);
        date.setSeconds(0, 0);  // 将秒和毫秒设置为0
        // if (date instanceof Date && !isNaN(date.getTime())) { // 检查date是否为有效日期
        //   this.form[field] = this.formatDateToValue(date);
        // }
      }
    },
    // formatDateToValue(date) {
    //     const year = date.getFullYear();
    //     const month = (date.getMonth() + 1).toString().padStart(2, '0');
    //     const day = date.getDate().toString().padStart(2, '0');
    //     const hours = date.getHours().toString().padStart(2, '0');
    //     const minutes = date.getMinutes().toString().padStart(2, '0');
    //     const seconds = '00'; // 秒值恒定设置为00
    //     return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    // },
    //获取教练信息
    getCouchInfo() {
      getCouchInfo().then((res) => {
        this.couchList = res.data
      })
    },
    //获取场馆最大人数
    getVenueMaxNumber() {
      getVenueMaxNumber().then((res) => {
        this.venueMaxNumber = res.data.maxNumber
      })
    },
    validateEndTime(rule, value, callback) {
      if (value && this.form.courseStartTime) {
        const startTime = new Date(this.form.courseStartTime);
        const endTime = new Date(value);
        if (endTime <= startTime) {
          callback(new Error('结束时间必须大于开始时间'));
          return;
        }
      }
      callback();
    },
    //报名时间验证
    validateRegistrationTime(rule, value, callback) {
      if (value) {
        const now = new Date();
        if (new Date(value) < now) {
          callback(new Error('报名时间不能低于当前时间'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请填写报名时间'));
      }
    },
    validateRegistrationDeadline(rule, value, callback) {
      if (value) {
        if (this.form.registrationTime && new Date(value) < new Date(this.form.registrationTime)) {
          callback(new Error('截止时间不能低于报名时间'));
        } else {
          callback();
        }
      } else {
        callback(new Error('请填写截止时间'));
      }
    },
    //表单验证是否为合法数字
    validateNumber(rule, value, callback) {
      if (value === '') {
        callback();
      } else if (!/^\d+$/.test(value)) {
        callback(new Error('请输入有效的数字'));
      } else {
        callback();
      }
    },
    //自定义规则校验
    validateLeastRegistrationNumber(rule, value, callback) {
      const max = parseInt(this.form.registrationNumber);

      // 尝试将输入值转换为整数
      const least = Number(value);

      // 检查转换后的值是否为有效数字
      if (isNaN(least)) {
        callback(new Error('请输入有效的数字'));
      } else if (least > max) {
        callback(new Error('至少报名数不能超过最大报名数'));
      } else {
        callback();
      }
    },
    // 启用禁用状态按钮
    toggleDisableStatus(row) {
      const id = row.id;
      this.$modal.confirm('确认是否发布吗? 发布后无法修改！！！')
        .then(() => {
          updateCourseStatus(id)
            .then((res) => {
              console.log(res.data.data)
              if (res.data.data > 0) {
                this.$message({type: "success", message: "发布成功"});
                this.getList();
              } else {
                this.$message({type: "error", message: "发布失败"});
                this.getList();
              }
            });
        }).catch(() => {
      });
    },
    /** 查询团课信息列表 */
    getList() {
      this.loading = true;
      listCourseSubscribe(this.queryParams).then(response => {
        this.courseSubscribeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        courseName: null,
        coverPic: null,
        courseDescribe: null,
        courseCreateTime: null,
        registrationNumber: null,
        registrationNumberLeast: null,
        collectFee: null,
        collectFeeMoney: null,
        courseStatus: null,
        venueUniqueIdentifier: null,
        courseStartTime: null,
        courseEndTime: null,
        registrationDeadline: null,
        registrationTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加团课信息";
      this.form.collectFee = 0;
      this.form.courseStatus = 0;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEditMode = true, //设为只读
      this.reset();
      const id = row.id || this.ids
      getCourseSubscribe(id).then(response => {
        this.form = response.data;
        console.log(response.data)
        this.open = true;
        this.title = "修改团课信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          var formdata = new FormData();
          var payWay = parseInt(this.form.payWay);
          formdata.set("payWay", payWay);
          formdata.set("id", this.form.id);
          formdata.set("couchId", this.form.couchId);
          formdata.set("courseName", this.form.courseName);
          formdata.set("courseDescribe", this.form.courseDescribe);
          formdata.set("registrationNumber", this.form.registrationNumber);
          formdata.set("registrationNumberLeast", this.form.registrationNumberLeast);
          formdata.set("collectFee", this.form.collectFee);
          formdata.set("collectFeeMoney", this.form.collectFeeMoney);
          formdata.set("courseStatus", this.form.courseStatus);
          formdata.set("venueUniqueIdentifier", this.venueUniqueIdentifier);
          formdata.set("registrationDeadline", this.form.registrationDeadline);
          formdata.set("registrationTime", this.form.registrationTime);
          formdata.set("courseStartTime", this.form.courseStartTime);
          formdata.set("courseEndTime", this.form.courseEndTime);
          if (this.form.coverPic != null && this.form.coverPic != undefined) {
            formdata.set("coverPic", this.form.coverPic);
          }
          if (this.form.id != null) {
            updateCourseSubscribe(formdata).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            formdata.set("id", 0)
            //判断是否收费 免费价格为0
            if (this.form.collectFee === 1) {
              formdata.set("collectFeeMoney", 0)
            }
            addCourseSubscribe(formdata).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    close() {
      this.open = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除团课信息编号为"  ' + row.courseName + '  "的数据项？').then(function () {
        return delCourseSubscribe(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('subscribe/courseSubscribe/export', {
        ...this.queryParams
      }, `courseSubscribe_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
